{isObject} = require 'lodash'


edit = (url, form_new, parse)->
    (to, from, next)->
        id = to.params.id
        form = await $.getJSON(url+(if id then "/"+id else ''))
        next(
            ->
                if form
                    if parse
                        form = parse.call(@, form) or form
                else
                    form = form_new()
                @added = 0
                Object.assign @form,form
        )

_form_new = (form)->
    ->
        $.extend( true, {}, form )

_success = (id)->
    @added = id

module.exports = (url, FORM, parse, err, success=_success)->
    form_new = _form_new(FORM)
    fetch = edit(url, form_new, parse)
    (mod)->
        data = mod.data
        mod.data = ->
            r = data.call(@)
            r.form = form_new()
            r.added = false
            r

        mod.beforeRouteUpdate = fetch

        mod.methods.submit = ->
            #submit前做处理
            f = true
            if mod.methods.beforeSubmit
                f = mod.methods.beforeSubmit.call(@)
            if f
                $(@$refs.form).save(
                    url
                    if isObject(f) then f else @form
                    =>
                        success.apply @,arguments
                    (tip)=>
                        err.call @, tip
                )

        mod.methods.reset = ->
            @$nextTick =>
                # 不然route还没变化
                if not @$route.params.id
                    @form = form_new()
                @added=false
                @$nextTick =>
                    $(@$refs.form).find("input:first").focus()

        mod
